using System.ComponentModel;
using System.Reflection;

namespace AdminApiTemplate.Common.Helpers
{
    public class EnumHelper
    {
        public static List<EnumItem> GetItems<T>() where T : struct
        {
            var pairs = new List<EnumItem>();
            var ttype = typeof(T);
            if (!ttype.IsEnum)
            {
                throw new Exception("需传入枚举类型");
            }

            var tfs = ttype.GetFields();
            var arr = Enum.GetValues(ttype);
            for (var i = 0; i < arr.Length; i++)
            {
                var obj = arr.GetValue(i);
                var val = (int)arr.GetValue(i);
                var description = GetDescription(tfs, obj, val);
                pairs.Add(new EnumItem
                {
                    Key = obj.ToString(),
                    Val = val,
                    Description = description
                });
            }

            return pairs.Where(w => w.Key != "None").ToList();
        }

        private static string GetDescription(FieldInfo[] tfs, object obj, int val)
        {
            foreach (var tf in tfs)
            {
                if (tf.FieldType == typeof(int))
                {
                    continue;
                }

                if ((int)tf.GetValue(obj) != val)
                {
                    continue;
                }

                var attr = tf.GetCustomAttribute<DescriptionAttribute>();
                if (attr != null)
                {
                    return attr.Description;
                }
                else
                {
                    return obj.ToString();
                }
            }

            return "";
        }
    }

    public class EnumItem
    {
        public string Key { get; set; }

        public int Val { get; set; }

        public string Description { get; set; }
    }
}
